package cn.com.dashihui.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.api.base.BaseController;
import cn.com.dashihui.api.common.ResultMap;
import cn.com.dashihui.api.common.SysConfig;
import cn.com.dashihui.api.dao.Goods;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.interceptor.WhenLoginInterceptor;
import cn.com.dashihui.api.service.GoodsService;

public class GoodsController extends BaseController{
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private GoodsService service = Duang.duang(GoodsService.class);
	
	
	/**
	 * 查找商品分类
	 */
	public void findCategory(){
		List<Record> list = service.findCategory();
		Record rec = new Record();
		List<Record> list1 = new ArrayList<Record>();
		List<Record> list2 = new ArrayList<Record>();
		List<Record> list3 = new ArrayList<Record>();
		List<Record> list4 = new ArrayList<Record>();
		List<Record> list5 = new ArrayList<Record>();
		if(list.size()>0&&list!=null){
			for(Record re : list){
				if(re.getInt("categoryType")==1){
					list1.add(re);
				}else if(re.getInt("categoryType")==2){
					list2.add(re);
				}else if(re.getInt("categoryType")==3){
					list3.add(re);
				}
			}
			if(list1.size()>0&&list1!=null){
				rec.set("first", list1);
			}
			if(list2.size()>0&&list2!=null){
				rec.set("second", list2);
			}
			if(list3.size()>0&&list3!=null){
				rec.set("three", list3);
			}
			renderSuccess(rec);
		}else{
			renderFailed("网络繁忙...，请稍后重试");
			return;
		}
	}
	
	
	/**
	 * 查询各优惠类型的一条商品信息
	 * @param STOREID 店铺ID
	 */
	public void topByType(){
		String storeid = getPara("storeid");
		Record type2 = service.topByType(2,storeid);
		Record type3 = service.topByType(3,storeid);
		Record type4 = service.topByType(4,storeid);
		renderSuccess(ResultMap.newInstance().put("TYPE2",type2).put("TYPE3", type3).put("TYPE4", type4));
	}
	
	/**
	 * 分页加载商品列表
	 * @param ONEID		一级类目
	 * @param TWOID		二级类目
	 * @param THREEID	三级类目
	 * @param ORDERBY 排序，1：默认排序，2：销量从高到低，3：价格从低到高，4：价格从高到低，V1.3.1以后用
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	public void list(){
		String storeid = getPara("storeid");
		String oneid = getPara("ONEID");
		int cateId = getParaToInt("cateId",0);
		String twoid = getPara("TWOID");
		String threeid = getPara("THREEID");
		if(StrKit.isBlank(oneid)){
			renderFailed("参数ONEID不能为空");
    		return;
		}else if(StrKit.isBlank(twoid)){
			renderFailed("参数TWOID不能为空");
    		return;
		}else if(StrKit.isBlank(threeid)){
			renderFailed("参数THREEID不能为空");
    		return;
		}
		int orderBy = getParaToInt("ORDERBY",1);
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		//严格判断一级分类代码
//		Prop prop = new Prop("realtime.properties",Const.DEFAULT_ENCODING);
		//根据不同的分类id（是否兑换），调用不同的查询方法
		Page<Record> page = null;
		if (cateId==0) {
			page = service.findByPage_v134(oneid,twoid,threeid,pageNum, pageSize,orderBy,storeid,cateId);
			//设置返回值，判断当前结果是否兑换商品
		}else if (cateId==1) {
			page = service.findByPage_v133(oneid,twoid,threeid,pageNum, pageSize,orderBy,storeid,cateId);
			//设置返回值，判断当前结果是否兑换商品
		}
		if(page == null){
			renderSuccess();
			return;
		}
		if(page.getPageSize()>0){
			renderSuccess(ResultMap.newInstance()
					.put("PAGENUMBER", page.getPageNumber())
					.put("PAGESIZE", page.getPageSize())
					.put("TOTALPAGE", page.getTotalPage())
					.put("TOTALROW", page.getTotalRow())
					.put("LIST", page.getList()));
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	/**
	 * 主页搜索框，点击查询所有商品
	 * @param ONEID		一级类目
	 * @param TWOID		二级类目
	 * @param THREEID	三级类目
	 * @param ORDERBY 排序，1：默认排序，2：销量从高到低，3：价格从低到高，4：价格从高到低，V1.3.1以后用
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	public void listAll(){
		
		String keyWord = getPara("KEYWORD");
		
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		//严格判断一级分类代码
//		Prop prop = new Prop("realtime.properties",Const.DEFAULT_ENCODING);
		//根据不同的分类id（是否兑换），调用不同的查询方法
		//查询普通商品
		Page<Record> page = service.findByPageAll(pageNum, pageSize,keyWord);
			//设置返回值，判断当前结果是否兑换商品
		//查询兑换商品
		Page<Record> page1 = service.findByPageAllAct(pageNum, pageSize,keyWord);
		
		List<Record> list = page.getList();
		List<Record> list1 = page1.getList();
		list.addAll(list1);
		if(page.getPageSize()>0){
			renderSuccess(ResultMap.newInstance()
					.put("PAGENUMBER", page.getPageNumber())
					.put("PAGESIZE", page.getPageSize())
					.put("TOTALPAGE", page.getTotalPage())
					.put("TOTALROW", page.getTotalRow())
					.put("LIST", list));
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	/**
	 * 商品标签列表<br/>
	 * 客户端首页用来查询所有商品标签，以及各标签下18条商品数据
	 * @param STOREID 店铺ID
	 */
	public void tags(){
		String storeidStr = getPara("STOREID");
		if(StrKit.isBlank(storeidStr)){
    		renderFailed("参数STOREID不能为空");
    		return;
		}else{
			renderSuccess(service.getAllTag(Integer.valueOf(storeidStr),18));
		}
	}
	
	/**
	 * 按标签查询商品列表
	 * @param STOREID 店铺ID
	 * @param TAGCODE 标签代码
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	public void listByTag(){
		String storeidStr = getPara("STOREID");
		String tagCode = getPara("TAGCODE");
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		if(StrKit.isBlank(storeidStr)){
    		renderFailed("参数STOREID不能为空");
    		return;
		}else if(StrKit.isBlank(tagCode)){
			renderFailed("参数TAGCODE不能为空");
    		return;
		}
		Page<Record> page = service.findPageByTag(Integer.valueOf(storeidStr), tagCode, pageNum, pageSize);
		
		renderSuccess(ResultMap.newInstance()
				.put("PAGENUMBER", page.getPageNumber())
				.put("PAGESIZE", page.getPageSize())
				.put("TOTALPAGE", page.getTotalPage())
				.put("TOTALROW", page.getTotalRow())
				.put("LIST", page.getList()));
	}
	
	/**
	 * 查询精品推荐商品列表
	 * @param STOREID 店铺ID
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	public void listByRecom(){
		String storeidStr = getPara("STOREID");
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		if(StrKit.isBlank(storeidStr)){
    		renderFailed("参数STOREID不能为空");
    		return;
		}
		Page<Record> page = service.findPageByRecom(Integer.valueOf(storeidStr), pageNum, pageSize);
		renderSuccess(ResultMap.newInstance()
				.put("PAGENUMBER", page.getPageNumber())
				.put("PAGESIZE", page.getPageSize())
				.put("TOTALPAGE", page.getTotalPage())
				.put("TOTALROW", page.getTotalRow())
				.put("LIST", page.getList()));
	}
    
	/**
	 * 商品详情
	 * @param GOODSID 商品ID
	 */
	@Before(WhenLoginInterceptor.class)
	public void detail(){
		String storeid= getPara("storeid");
		String goodsidStr = getPara("GOODSID");
		String isSpike = getPara("SPIKE");
		int isLook = getParaToInt("ISLOOK",0);
		if(StrKit.isBlank(isSpike)){
			isSpike = "0";
		}
		if(StrKit.isBlank(goodsidStr)){
			renderFailed("参数GOODSID不能为空");
			return;
		}else{
			//是商品详情页
			if(isLook==1){
				if(service.updateLookByid(goodsidStr)!=1){
//					renderFailed("更新浏览量失败");
				}
			}
			//查询商品详情信息
			Record goods;
			if(getCurrentUser()!=null){
				//如果当前有用户登录，则查询商品详情的同时，查询该用户与该商品的收藏关系
				goods = service.findDetail(getCurrentUser().getInt("id"), Integer.valueOf(goodsidStr),storeid);
			}else{
				//如果当前没有用户登录，则只查询商品详情
				goods = service.findDetail(Integer.valueOf(goodsidStr),storeid);
			}
			if(goods!=null){
				//查询商品的图片集，并遍历拼成数组形式，如：["/goods/xxx1.jpg","goods/xxx2.jpg"]
				List<Record> images = service.findImages(goods.getStr("LUNBONUM"));
				List<String> strList = new ArrayList<String>();
				if(images!=null&&images.size()!=0){
					for(Record image : images){
						strList.add(image.getStr("THUMB"));
					}
				}
				//查询商品的特殊规格集，并便利拼成数组形式
				List<Record> specs = service.findSpec(Integer.valueOf(goodsidStr) );
				if(specs!=null&&specs.size()!=0){
					if(Integer.valueOf(isSpike)==1){
						//查询秒杀表信息
						Record rec = service.findSpike(specs.get(0).getInt("goodsid"));
						goods.set("SPIKE", rec);
						goods.set("SPEC", specs.get(0));
					}else{
						goods.set("SPEC", specs);
					}
				}
				//查询商品的普遍规格集，并便利拼成数组形式
				List<Record> items = service.findComSpec(Integer.valueOf(goodsidStr));
				if(items!=null&&items.size()!=0){
					goods.set("Comspec", items);
				}
				//邮费
				Double postAge = 0.00;
				Double postAgeFree = 0.00;
				try {
					postAge = SysConfig.getPostAge();
					postAgeFree = SysConfig.getPostAgeFree();
				} catch (Exception e) {
					renderFailed("查询邮费失败");
					return;
				}
				goods.set("postAge", postAge);
				goods.set("postAgeFree", postAgeFree);
				//设置给商品详情信息
				goods.set("IMAGES", strList);
				renderSuccess(goods);
			}else{
	    		renderFailed("商品不存在");
			}
		}
	}
	/**
	 * 充值卡详情
	 * @param GOODSID 商品ID
	 */
	@Before(WhenLoginInterceptor.class)
	public void detail1(){
		String goodsidStr = getPara("GOODSID");
		if(StrKit.isBlank(goodsidStr)){
			renderFailed("参数GOODSID不能为空");
			return;
		}else{
			//查询商品详情信息
			Record goods = service.findDetail1(Integer.valueOf(goodsidStr));
			if(goods!=null){
				renderSuccess(goods);
			}else{
	    		renderFailed("商品不存在");
			}
		}
	}
	
	/**
	 * 商品详情描述
	 * @param GOODSID 商品ID
	 */
	public void detailDescribe(){
		String storeid= getPara("storeid");
		String goodsidStr = getPara("GOODSID");
		
		if(StrKit.isBlank(goodsidStr)){
    		renderFailed("参数GOODSID不能为空");
    		return;
		}else{
			Goods goods = new Goods();
			List<Record> describes = service.findDetailDescribe(Integer.valueOf(goodsidStr),storeid);
			List<String> detailList = new ArrayList<String>();
			if(describes!=null&&describes.size()!=0){
				for(Record detail : describes){
					detailList.add(detail.getStr("THUMB"));
				}
			}
			goods.set("DESCRIBE", detailList);
			renderSuccess(goods);
			return;
		}
	}
	
	/**
	 * 根据商品ID查询三级分类ID
	 */
	public void queryGoodsCate() {
		String goodsid=getPara("GOODSID");
		if(StrKit.isBlank(goodsid)){
    		renderFailed("参数GOODSID不能为空");
    		return;
		}
		Record cate=service.queryGoodsCate(Integer.valueOf(goodsid));
		renderSuccess(cate);
	}
	
	/**
	 * 查询同类商品
	 */
	public void findOtherGoodsSamecate() {
		String storeid= getPara("storeid");
		String goodsid=getPara("GOODSID");
		String page=getPara("PAGE");
		if (StrKit.isBlank(page)) {
			renderFailed("参数page不能为空");
    		return;
		}
		if(StrKit.isBlank(goodsid)){
    		renderFailed("参数GOODSID不能为空");
    		return;
		}
		if ("1".equals(page)&&!"undefined".equals(goodsid)) {
			List<Record> otherGoods=service.findOtherGoodsSamecate(Integer.valueOf(goodsid),storeid);
			renderSuccess(otherGoods);
		}else  if("2".equals(page)&&!"undefined".equals(goodsid)){
			List<Record> otherGoods=service.findOtherGoodsSamecateEge(Integer.valueOf(goodsid));
			renderSuccess(otherGoods);
		}else {
			renderFailed();
		}
	}
	
	/**
	 * 查询秒杀列表
	 */
	public void spikeList(){
		String storeid= getPara("storeid");
		
		List<Record> records = service.findSpikeList();
		if(records!=null && records.size()>0){
			Map<String,List<Record>> map = new HashMap<String,List<Record>>();
			Map<String,List<Record>> newmap =null;
			List<Record> cord = null;
		
			map.put(SysConfig.spikeTime.SIX, cord);
			map.put(SysConfig.spikeTime.EIGHT, cord);
			map.put(SysConfig.spikeTime.TEN, cord);
			map.put(SysConfig.spikeTime.TWELVE, cord);
			map.put(SysConfig.spikeTime.FOURTH, cord);
			map.put(SysConfig.spikeTime.SIXTH, cord);
			map.put(SysConfig.spikeTime.EIGHTH, cord);
			map.put(SysConfig.spikeTime.TWENTY, cord);
			map.put(SysConfig.spikeTime.TWENTYTWO, cord);
			map.put(SysConfig.spikeTime.ZERO, cord);
			map.put(SysConfig.spikeTime.TWO, cord);
			map.put(SysConfig.spikeTime.FOUR, cord);
			for(Record record : records){
				//查找详细商品信息
				newmap = service.findGoodsByid(map,record,storeid);
			}
			renderSuccess(newmap);
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	
	
	/**
	 * 新鲜好物，人气推荐，专题精选，品牌制造商,优选，亿品，传媒
	 */
	public void fresh(){
		String storeid = getPara("storeid");
		int type = getParaToInt("TYPE",0);
		String gp = getPara("GP");
		if(StrKit.isBlank(gp)){
			renderFailed("参数GP不能为空");
    		return;
		}
		List<Record> list = service.findFresh(gp,storeid,type);
		if(list!=null && list.size()>0){
			renderSuccess(list);
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
		
	}
	/**
	 * CIDS sale表的id集合
	 * 购物车列表
	 */
	public void cartList(){
		String storeid= getPara("storeid");
		String cids = getPara("CIDS");
		if(StrKit.isBlank(cids)){
			renderFailed("参数CIDS不能为空");
    		return;
		}
		List<Record> list = service.findSaleByCids(cids,storeid);
		Record re = new Record();
		//邮费
		Double postAge = 0.00;
		Double postAgeFree = 0.00;
		try {
			postAge = SysConfig.getPostAge();
			postAgeFree = SysConfig.getPostAgeFree();
		} catch (Exception e) {
			renderFailed("查询邮费失败");
			return;
		}
		re.set("postAgeFree", postAgeFree);
		re.set("postAge", postAge);
		if(list!=null&&list.size()>0){
			re.set("list", list);
			renderSuccess(re);
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	/**
	 * 查询兑换titile列表
	 */
	public void exchangeList(){
		List<Record> list = service.findTitleList();
		if(list!=null&&list.size()>0){
			renderSuccess(list);
		}
		else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	
	/**
	 * 兑换页面列表
	 */
	public void exchange(){
		String lableId = getPara("LID");
		if(StrKit.isBlank(lableId)){
			renderFailed("参数LID不能为空");
    		return;
		}
		
		List<Record> list = service.findExchangeList(lableId);
		Record res = service.findTitle(lableId);
		
		if(list!=null&&list.size()>0){
			List<Record> newlist = new ArrayList<Record>();
			//筛选
			for(Record re : list){
				String str = re.get("lableId");
				if(str.contains(lableId)){
					re.set("lable",res.get("title"));
					re.set("lableId",lableId);
					newlist.add(re);
				}
			}
			if(newlist!=null&&newlist.size()>0){
				renderSuccess(newlist);
			}
			else{
				renderFailed("网络繁忙...，请稍后重试");
			}
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	/**
	 * 兑换商品详情
	 */
	public void exchangeDetail(){
		String id = getPara("ID");
		int isLook = getParaToInt("ISLOOK",0);
		if(StrKit.isBlank(id)){
			renderFailed("参数ID不能为空");
    		return;
		}
		if(isLook==1){
			if(service.updateLookByidExchange(id)!=1){
//				renderFailed("更新浏览量失败");
			}
		}
		
		List<Record> list = service.findExchangeDetailList(id);
		if(list!=null&&list.size()>0){
			//查询商品的图片集，并遍历拼成数组形式，如：["/goods/xxx1.jpg","goods/xxx2.jpg"]
			List<Record> images = service.findImages(list.get(0).getStr("LUNBONUM"));
			List<String> strList = new ArrayList<String>();
			if(images!=null&&images.size()!=0){
				for(Record image : images){
					strList.add(image.getStr("THUMB"));
				}
			}
			Record re = new Record();
			//邮费
			Double postAge = 0.00;
			Double postAgeFree = 0.00;
			try {
				postAge = SysConfig.getPostAge();
				postAgeFree = SysConfig.getPostAgeFree();
			} catch (Exception e) {
				renderFailed("查询邮费失败");
				return;
			}
			re.set("postAgeFree", postAgeFree);
			re.set("postAge", postAge);
			re.set("list", list);
			re.set("LUNBONUM",strList);
			renderSuccess(re);
		}else{
			renderFailed("网络繁忙...，请稍后重试");
		}
	}
	
	/**
	 * 兑换商品详情描述
	 * @param GOODSID 商品ID
	 */
	public void exchangeDetailDescribe(){
		String goodsidStr = getPara("GOODSID");
		
		if(StrKit.isBlank(goodsidStr)){
    		renderFailed("参数GOODSID不能为空");
    		return;
		}else{
			Goods goods = new Goods();
			List<Record> describes = service.findExchangeDetailDescribe(Integer.valueOf(goodsidStr));
			List<String> detailList = new ArrayList<String>();
			if(describes!=null&&describes.size()!=0){
				for(Record detail : describes){
					detailList.add(detail.getStr("THUMB"));
				}
			}
			goods.set("DESCRIBE", detailList);
			renderSuccess(goods);
			return;
		}
	}
	
	
	/**
	 * 查询商品评价
	 * 商品ID
	 * 是否是兑换商品
	 * 是否只需要一条
	 */
	public void commentlist(){
		String storeid= getPara("storeid");
		String id = getPara("ID");
		String isExchange = getPara("ISEXCHANGE");
		String isOne = getPara("ISONE");
		if(StrKit.isBlank(id)){
			renderFailed("参数ID不能为空");
    		return;
		}else if(StrKit.isBlank(isExchange)){
			renderFailed("参数ISEXCHANGE不能为空");
    		return;
		}else if(StrKit.isBlank(isOne)){
			renderFailed("参数ISONE不能为空");
    		return;
		}
		List<Record> list = service.findCommentById(id,isExchange,storeid);
		if(list!=null && list.size()>0){
			Record re = new Record();
			if("1".equals(isOne)){
				re.set("size", list.size());
				//组装评论图片
				List<Record> reslist = service.findImageByLunBoNum(list.get(0).getStr("LunBoNum"));
				if(reslist!=null && reslist.size()>0){
					List<String> imagelist = new ArrayList<String>();
					for(Record res : reslist){
						imagelist.add(res.getStr("thumb"));
					}
					re.set("images", imagelist);
				}
				//组装用户信息
				if(list.get(0).getInt("flag")!=1){
					User user = User.me().findById(list.get(0).get("userid"));
					String name = null;
					if(user.get("name")!=null){
						name = user.get("name");
						
					}
					list.get(0).set("name", name);
					list.get(0).set("img", user.get("avator"));
				}else{
					list.get(0).set("name", "用户");
					list.get(0).set("img", null);
				}
				re.set("list", list.get(0));
				renderSuccess(re);
			}else{
				renderSuccess(list);
			}
		}else{
			renderSuccess();
		}
	}
}
